<template>
  <div class="app-container">
    <v-row :gutter="20">
      <v-col>
        <!-- 搜索表单 -->
        <v-form ref="queryForm" v-show="showSearch" label-width="68px">
          <v-row>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="公告标题"
                v-model="queryParams.noticeTitle"
                placeholder="请输入公告标题"
                outlined
                dense
                clearable
                @keyup.enter.native="handleQuery"
                style="width: 240px;"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px">
              <v-text-field
                label="操作人员"
                v-model="queryParams.createBy"
                placeholder="请输入操作人员"
                outlined
                dense
                style="width: 240px;"
                @keyup.enter.native="handleQuery"
              ></v-text-field>
            </v-col>
            <v-col md="2" style="padding-bottom: 2px;max-width: 150px">
              <v-select
                label="类型"
                v-model="queryParams.noticeType"
                :items="typeOptions"
                item-text="dictLabel"
                item-value="dictValue"
                placeholder="公告类型"
                dense
                outlined
                clearable
                style="width: 130px;"
              ></v-select>
            </v-col>

            <!-- 按钮区-->
            <v-col cols="12"
                   sm="6"
                   md="2" style="padding-bottom: 0;margin-left: 1rem;height: 40px;margin-top: 8px">
              <p style="display: inline-block;position: absolute">
                <v-btn
                  small color="primary"
                  :loading="loading"
                  @click="handleQuery">
                  <v-icon left>
                    mdi-magnify
                  </v-icon>
                  搜索
                </v-btn>
                <v-btn
                  small
                  :loading="loading"
                  @click="resetQuery"
                  style="margin-left: 10px"
                >
                  <v-icon left>
                    mdi-autorenew
                  </v-icon>
                  重置
                </v-btn>
              </p>
            </v-col>
          </v-row>
        </v-form>
      </v-col>
    </v-row>

    <!-- 表格操作按钮区 -->
    <v-row style="margin-bottom: -5px;margin-top: 0;">
      <v-col md="1" style="max-width: 84px">
        <v-btn
          color="primary"
          plain
          small
          outlined
          @click="handleAdd"
          v-hasPermi="['system:notice:add']">
          <v-icon left>
            mdi-plus
          </v-icon>
          新增
        </v-btn>
      </v-col>
      <v-col md="1" style="max-width: 84px">
        <v-btn
          small
          plain
          outlined
          :disabled="single"
          @click="handleUpdate(ids[0])"
          v-hasPermi="['system:notice:edit']">
          <v-icon left>
            mdi-pencil
          </v-icon>
          修改
        </v-btn>
      </v-col>
      <!--todo 二次删除确认 -->
      <v-col md="1" style="max-width: 84px">
        <v-btn
          small color="error"
          plain
          outlined
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notice:remove']">
          <v-icon left>
            mdi-delete
          </v-icon>
          删除
        </v-btn>
      </v-col>
      <v-col style="float: right">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </v-col>
    </v-row>

    <el-row :gutter="10" class="mb8" v-if="false">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:notice:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:notice:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格-->
    <v-main>
      <v-data-table v-if="noticeList"
                    v-model="ids"
                    :headers="headers"
                    :items="noticeList"
                    :items-per-page="queryParams.pageSize"
                    hide-default-footer
                    :loading="loading"
                    loading-text="加载中,请稍后.."
                    show-select
                    item-key="noticeId"
                    class="elevation-1"
                    no-data-text="暂无数据"
      >

        <!-- 公告类型 插槽 -->
        <template v-slot:item.status="{ item }">
          {{ typeFormat(item) }}
        </template>
        <!-- 状态插槽 -->
        <template v-slot:item.status="{ item }">
          {{ statusFormat(item) }}
        </template>

        <!-- 按钮插槽 -->
        <template v-slot:item.actions="{ item }">
          <v-btn text
                 small
                 plain
                 height="20"
                 width="40"
                 @click="handleUpdate(item)"
                 v-hasPermi="['system:role:edit']">
            <v-icon small>
              mdi-pencil
            </v-icon>
            修改
          </v-btn>
          <span v-if="item && !item.showConfirmDelete">
            <v-btn color="#C62828"
                   small
                   plain
                   height="20"
                   width="40"
                   @click="onClickDelete(item)">
              <v-icon small>
                mdi-delete
              </v-icon>
              删除
            </v-btn>
          </span>
          <!-- 删除确认 -->
          <span v-else>
            <v-tooltip top>
              <template v-slot:activator="{ on, attrs }">
                <v-btn
                  small color="error"
                  plain
                  height="20"
                  width="40"
                  v-bind="attrs"
                  v-on="on"
                  @click="handleDelete(item)"
                  v-hasPermi="['system:role:remove']">
                  <v-icon small>
                    mdi-delete
                  </v-icon>
                  确定
                </v-btn>
              </template>
              <span>请再次点击确定删除</span>
            </v-tooltip>
          </span>
        </template>
      </v-data-table>
      <!-- 外部分页-->
      <div class="d-flex align-center justify-end text-center">
        <div class="d-flex" style="margin-top: 3px;font-size: 14px;font-weight: 400">
          <span>每页</span>
          <v-select
            v-model="queryParams.pageSize"
            :items="numbers"
            dense
            @change="getList" style="max-width: 80px;max-height: 20px;margin-top: -4px;text-align: center;">
            <template v-slot:selection="{ item, index }">
                  <span style="width: 100%">
                    {{item}}
                  </span>
            </template>
          </v-select>
          <span>条记录</span>
        </div>
        <v-pagination
          v-model="queryParams.pageNum"
          @input="getList"
          :length="queryParams.totalPages"
          :total-visible="7"
        ></v-pagination>
      </div>
    </v-main>

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="noticeType">
              <el-select v-model="form.noticeType" placeholder="请选择">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容">
              <editor v-model="form.noticeContent" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <notice-add ref="addNoticeRef" :visible.sync="showAdd" @updateVisible="updateVisible" @done="handleQuery"
                :statusOptions="statusOptions" :typeOptions="typeOptions"></notice-add>

    <notice-edit ref="editNoticeRef" :visible.sync="showEdit" :data="form" @updateVisible="updateVisible" @done="handleQuery"
                :statusOptions="statusOptions" :typeOptions="typeOptions"></notice-edit>
  </div>
</template>

<script>
import { listNotice, getNotice, delNotice, addNotice, updateNotice } from "@/api/system/notice";
import Editor from '@/components/Editor';
import NoticeAdd from './noticeAdd';
import NoticeEdit from './noticeEdit';

export default {
  name: "Notice",
  components: {
    Editor,
    NoticeAdd,
    NoticeEdit
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      noticeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showAdd: false,
      showEdit: false,
      // 类型数据字典
      statusOptions: [],
      // 状态数据字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        noticeTitle: undefined,
        createBy: undefined,
        status: undefined,
        totalPages: 0, // 总页数
      },
      // 表单参数
      form: {},
      headers: [
        { text: '序号', value: 'noticeId', align: 'center' },
        { text: '公告标题', value: 'noticeTitle', sortable: false, align: 'center' },
        { text: '公告类型', value: 'noticeType', sortable: false, align: 'center' },
        { text: '状态', value: 'status', sortable: false, align: 'center' },
        { text: '创建者', value: 'createBy', sortable: false, align: 'center' },
        { text: '创建时间', value: 'createTime', sortable: false, align: 'center' },
        { text: '操作', value: 'actions', sortable: false, align: 'center' },
      ],
      numbers: [10, 15, 20, 50, 100], // 每页条数选择
      // 表单校验
      rules: {
        noticeTitle: [
          { required: true, message: "公告标题不能为空", trigger: "blur" }
        ],
        noticeType: [
          { required: true, message: "公告类型不能为空", trigger: "blur" }
        ]
      }
    };
  },
  watch: {
    ids() {
      this.handleSelectionChange();
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_notice_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_notice_type").then(response => {
      this.typeOptions = response.data;
    });
  },
  methods: {
    /** 查询公告列表 */
    getList() {
      this.ids = [];
      this.loading = true;
      listNotice(this.queryParams).then(response => {
        this.noticeList = response.rows;
        this.total = response.total;
        this.queryParams.totalPages = Math.ceil(this.total / this.queryParams.pageSize);
        this.loading = false;
      });
    },
    // 公告状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 公告状态字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.noticeType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        noticeId: undefined,
        noticeTitle: undefined,
        noticeType: undefined,
        noticeContent: undefined,
        status: "0"
      };
      //this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryForm.reset(); // 重置
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      this.single = this.ids.length !== 1;
      this.multiple = !this.ids.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.showAdd = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const noticeId = row.noticeId || this.ids
      getNotice(noticeId).then(response => {
        this.form = response.data;
        this.showEdit = true;
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.noticeId != undefined) {
            updateNotice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addNotice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 表格列点击删除按钮，切换确定删除按钮
    onClickDelete(item) {
      this.$set(item, 'showConfirmDelete', true);
      setTimeout(() => {
        this.$set(item, 'showConfirmDelete', false);
      }, 3500);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      // 关闭上一个消息弹窗
      this.$store.commit("snackbar/CLOSE_SNACKBAR");
      const noticeIds = row.noticeId || this.ids.map(item => item.noticeId);
        await delNotice(noticeIds).then(res => {
          if (res) {
            // 使用全局消息提示
            this.$store.dispatch('snackbar/openSnackbar', {
              msg: '删除成功',
              color: 'success'
            })
            this.getList()
          }
        })
    },
    updateVisible(value) {
      this.showAdd = value;
      this.showEdit = value;
    },
  }
};
</script>
